import { Space, Switch, Table, Button, Popconfirm, Spin } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import type { TableRowSelection } from 'antd/es/table/interface'
import React, { useState, useEffect, useRef } from 'react'
import * as Icons from '@ant-design/icons'
import CommonDialog from '@/components/commonDialog'
import FormConfig from './components/formConfig'
import { PlusOutlined } from '@ant-design/icons'
import { editmenuApi, addmenufirst, addmenulower, deletemenu } from './api'
import { getInfoApi } from '@/api/info'
import Store from '@/store'

interface DataType {
    key: string
    label: string
    icon: string
    url: string
    parentKey?: string
    sort: number
    children?: DataType[]
}

const rowSelection: TableRowSelection<DataType> = {
    onChange: (selectedRowKeys, selectedRows) => {
        console.log(
            `selectedRowKeys: ${selectedRowKeys}`,
            'selectedRows: ',
            selectedRows
        )
    },
    onSelect: (record, selected, selectedRows) => {
        console.log(record, selected, selectedRows)
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
        console.log(selected, selectedRows, changeRows)
    },
}

const App: React.FC = () => {
    const [checkStrictly] = useState(false)
    const [data, setData] = useState<DataType[]>([])
    const [dialogOpen, setDialogOpen] = useState(false)
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [title, setTitle] = useState('')
    const [loading, setLoading] = React.useState<boolean>(false)
    const formRef = useRef<any>(null)
    const userId = Store((state) => state.userId)

    useEffect(() => {
        fetchData()
    }, [])
    // 获取数据
    function fetchData() {
        setLoading(true)
        try {
            getInfoApi({ userId })
                .then((res: any) => {
                    setData(res.data.path || [])
                })
                .finally(() => {
                    setLoading(false)
                })
        } catch (error) {
            console.log('获取数据失败', error)
            setLoading(false)
        }
    }
    const columns: ColumnsType<DataType> = [
        // 定义表格列
        {
            title: '名称',
            dataIndex: 'label',
            key: 'label',
        },
        {
            title: '图标',
            dataIndex: 'icon',
            key: 'icon',
            width: '12%',
            render: (_, { icon }) => {
                const IconComp = icon && Icons[icon]
                return IconComp ? <IconComp /> : null
            },
        },
        {
            title: '路径',
            dataIndex: 'url',
            width: '30%',
            key: 'url',
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link" onClick={() => handleEdit(record)}>
                        编辑
                    </Button>
                    <Button type="link" onClick={() => bindAddSub(record)}>
                        添加下级
                    </Button>
                    <Popconfirm
                        title="你确定删除吗?"
                        onConfirm={() => bindDetele(record.key)}
                    >
                        <Button type="link">删除</Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ]

    function handleEdit(record: DataType) {
        // 编辑
        setTitle('编辑权限')
        setDialogOpen(true)

        // 等待弹窗打开后，再设置表单数据
        setTimeout(() => {
            formRef.current?.setFieldsValue(record)
        }, 0)
    }

    // 添加下级
    function bindAddSub(record: DataType) {
        setTitle('添加下级')
        setDialogOpen(true)
        // 等待弹窗打开后，再设置表单数据
        setTimeout(() => {
            formRef.current?.setFieldsValue({ parentKey: record.key })
        }, 0)
    }
    function bindDetele(key: string) {
        // 删除
        console.log('删除', key)
        deletemenu({ key }).then((res) => {
            // 重新获取数据
            fetchData()
        })
    }
    function bindAddClub() {
        // 添加同级
        setTitle('添加菜单')
        setDialogOpen(true)
    }
    const handleDialogOk = async () => {
        // 获取表单数据
        const values = await formRef.current.submit()
        console.log('表单数据：', values)
        // 弹窗确定按钮，触发表单校验
        setConfirmLoading(true)
        if (title === '编辑权限') {
            // 编辑或新增的接口请求
            editmenuApi(values).then((res) => {
                setConfirmLoading(false)
                setDialogOpen(false)
                // 重置表单
                formRef.current?.reset()
                // 重新获取数据
                fetchData()
            })
        } else if (title === '添加下级') {
            addmenulower(values)
                .then((res) => {
                    setConfirmLoading(false)
                    setDialogOpen(false)
                    // 重置表单
                    formRef.current?.reset()
                    // 重新获取数据
                    fetchData()
                })
                .finally(() => {
                    setConfirmLoading(false)
                })
        } else {
            addmenufirst(values)
                .then((res) => {
                    setConfirmLoading(false)
                    setDialogOpen(false)
                    // 重置表单
                    formRef.current?.reset()
                    // 重新获取数据
                    fetchData()
                })
                .finally(() => {
                    setConfirmLoading(false)
                })
        }
    }

    const handleDialogCancel = () => {
        // 重置表单
        formRef.current?.reset()
        setDialogOpen(false)
    }
    return (
        <>
            <Spin spinning={loading}>
                <Button
                    type="primary"
                    className="mb-2"
                    onClick={() => bindAddClub()}
                >
                    <PlusOutlined />
                    新增一级菜单
                </Button>
                <Table
                    bordered
                    columns={columns}
                    rowSelection={{ ...rowSelection, checkStrictly }}
                    dataSource={data}
                />
                <CommonDialog
                    open={dialogOpen}
                    title={title}
                    width={600}
                    confirmLoading={confirmLoading}
                    onOk={handleDialogOk}
                    onCancel={handleDialogCancel}
                >
                    <FormConfig ref={formRef} />
                </CommonDialog>
            </Spin>
        </>
    )
}

export default App
